//
//  BSStatusViewModel.swift
//  mySwiftWeibo
//
//  Created by apple on 16/7/29.
//  Copyright © 2016年 itcast沈庆伟. All rights reserved.
//

import UIKit

//微博模型ViewModel,处理微博模型相关操作
class BSStatusViewModel: NSObject {

    ///单例
    static let sharedStatusViewModel: BSStatusViewModel = BSStatusViewModel()
    
    ///加载微博数据的方法
    func loadStatus(since_id: Int64, max_id: Int64, completion: (error: NSError?, statusModels: [BSStatus]?) -> Void){
        //守卫
        guard let access_token = BSUserAccountViewModel.sharedUserAccountViewModel.userAccount?.access_token else{
            //access_token 没有值
            print("access_token 没有值")
            return
        }
        
        //urlstring
        let urlString = "2/statuses/home_timeline.json"
        var parameters: [String: AnyObject] = [
            "access_token": access_token
        ]
        
        //如果传入的since_id
        if since_id > 0 {
            parameters["since_id"] = NSNumber(longLong: since_id)
        }else if max_id > 0 {
            parameters["max_id"] = NSNumber(longLong: max_id)
        }
        
        //发送请求
        BSNetWorkTool.sharedNetworkTool.GET(urlString, parameters: parameters, progress: nil, success: { (_, responseObject) -> Void in
            
            //返回的字典
            let responseDict = responseObject as? [String: AnyObject]
            
            //微博字典数组
            let statusesArray = responseDict?["statuses"] as? [[String: AnyObject]]
            
            //模型数组
            var statusModels = [BSStatus]()
            
            //遍历
            for dict in statusesArray!{
                //转模型
                let status = BSStatus(dict: dict)
                
                //保存
                statusModels.append(status)
            }
            
            //返回模型数组
            completion(error: nil, statusModels: statusModels)
            
            }) { (_, error) -> Void in
                completion(error: error, statusModels: nil)
        }

    }
}
